package repository

import (
	"gitee.com/ysl729895/go-mall/internal/model"
	"gorm.io/gorm"
)

// RolePermissionRepository 角色-权限关联数据操作接口
//go:generate mockgen -source=role_permission_repository.go -destination=mock_role_permission_repository.go -package=repository

type RolePermissionRepository interface {
	Create(rolePermission *model.RolePermission) error
	DeleteByRoleID(roleID uint) error
	GetPermissionsByRoleID(roleID uint) ([]model.Permission, error)
}

type rolePermissionRepository struct {
	db *gorm.DB
}

func NewRolePermissionRepository(db *gorm.DB) RolePermissionRepository {
	return &rolePermissionRepository{db: db}
}

func (r *rolePermissionRepository) Create(rolePermission *model.RolePermission) error {
	return r.db.Create(rolePermission).Error
}

func (r *rolePermissionRepository) DeleteByRoleID(roleID uint) error {
	return r.db.Where("role_id = ?", roleID).Delete(&model.RolePermission{}).Error
}

func (r *rolePermissionRepository) GetPermissionsByRoleID(roleID uint) ([]model.Permission, error) {
	var permissions []model.Permission
	err := r.db.Table("role_permissions").Select("permissions.*").Joins("left join permissions on role_permissions.permission_id = permissions.id").Where("role_permissions.role_id = ?", roleID).Scan(&permissions).Error
	return permissions, err
}
